<?php 
/****
布尔教育 高端PHP培训
培  训: http://www.itbool.com
论  坛: http://www.zixue.it
****/

abstract class aDB {
/**
* ᬳളහഝପ,՗ᯈᗝ෈կ᧛ᯈݐᗝ௳מ
*/
abstract public function conn();
/**
* ݎᭆqueryັᧃ
* @param string $sql sql᧍ݙ
* @return mixed
*/
abstract public function query($sql);
/**
* ັᧃग़ᤈහഝ
* @param string $sql sql᧍ݙ
* @return array
*/
abstract public function getAll($sql);
/*** ܔᤈහഝ
* @param string $sql sql᧍ݙ
* @return array
*/
abstract public function getRow($sql);
/**
* ັᧃܔӻහഝ ই count(*)
* @param string $sql sql᧍ݙ
* @return mixed
*/
abstract public function getOne($sql);
/**
* ᛔۖڠୌsqlଚಗᤈ
* @param array $data ىᘶහᕟ Ძ/؀Өᤒጱ/ڜ؀੒ଫ
* @param string $table ᤒਁݷ
* @param string $act ֢ۖ/update/insert
* @param string $where ๵կ,አԭupdate
* @return int ෛൊفጱᤈጱԆᲫ؀౲୽ߥᤈහ
*/
abstract public function Exec($data , $table , $act='insert' , $where='0');
/**
* ᬬࢧӤӞ๵insert᧍ݙԾኞጱԆᲫ؀
*/
abstract public function lastId();
/**
* ᬬࢧӤӞ๵᧍ߥ୽ݙጱᤈහ
*/
abstract public function affectRows();
}


class Mysql extends aDB{
	public $link;	
	public function __construct(){
		$this->conn();
	}
	/**
	* 连接数据库,从配置文件读取配置信息
	*/
	public function conn(){
		$cfg = include './config.php';
		$this->link = new mysqli($cfg['host'], $cfg['user'], $cfg['pwd'], $cfg['db']);
		$this->query('set names '.$cfg['charset']);
	}
	public function query($sql){
		return $this->link->query($sql);
	}
	public function getAll($sql){
		$data = [];
		$res = $this->query($sql);
		while ($row = $res->fetch_assoc()){
			$data[] = $row;
		}
		return $data;
	}

	public function getRow($sql){
		$res = $this->query($sql);
		$row = $res->fetch_assoc();
		return $row;
	}

	public function getOne($sql){
		$res = $this->query($sql);
		$row = $res->fetch_row()[0];
		return $row;
	}

	public function Exec($data , $table , $act='insert' , $where='0'){
		/*if ($act = 'insert') {
			//插入语句
			$sql = 'insert into '.$table .' (';
			$sql .= implode(',' , array_keys($data)).') ';
			$sql .= "values ('";
			$sql .= implode("','",array_values($data))."')";
		} else {
			//update
			$sql = "update $table set ";
			foreach ($data as $k => $v) {
				$sql.= $k."='".$v."',";
			}
			$sql = rtrim($sql,',');
			$sql .= " where $where";
		}*/
		if ($act === 'insert') {
			$sql = 'insert into '.$table.' (';
			$sql .= implode(',', array_keys($data)).") values ('";
			$sql .= implode("','", array_values($data))." ')";
			//return $sql;
			return $this->query($sql);
		}else if($act === 'update'){
			$sql = 'update ' . $table. ' set ';
			foreach ($data as $k => $v) {
				$sql .= " $k = '$v',";
			}
			$sql = rtrim($sql,',');
			$sql .= ' where '.$where;
			return $this->query($sql);
		}
	}
	public function lastId(){
		return $this->link->insert_id;
	}
	public function affectRows(){
		return $this->link->affected_rows;
	}
}

$mysql = new Mysql();
$mysql->Exec(['email'=>'xiaoye','nick'=>'30'],'user','insert','user_id=3');
var_dump($mysql->lastId());
?>